<?php

namespace App\Http\Controllers\Frontend\V10\UnionLogin;

use App\Constant\SmsTemplate;
use App\Library\ArrayTools\ArrayTools;
use App\Library\String\Strings;
use App\Library\String\UnionLoginTools;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class HelpWalletController extends Controller
{
    //app 下载地址
    const LOAD_URL = "https://manage.longloan.cn/#/download";
    const HELP_WALLET_PRIVATE_KEY = "5962e907adf085e9";
    //注册时，返回的用户状态
    const UNION_USER_STATUS_NEW = 1; //新用户
    const UNION_USER_STATUS_OLD = 2; //老用户
    const UNION_USER_STATUS_BLACK_NAME = 3; //黑名单
    const UNION_USER_STATUS_OTHER = -1; //其他
    /**
     * 连登返回code
     */
    const UNION_CODE_SUCCESS = '0000';//成功
    const UNION_CODE_DECRYPT_EXCEPTION = '1001';//解密异常
    const UNION_CODE_SIGN_EXCEPTION = '1002';//签名异常
    const UNION_CODE_PARAMS_EXCEPTION = '1003';//参数异常
    const UNION_CODE_NET_EXCEPTION = '1004';//网络异常
    const UNION_CODE_OTHER_EXCEPTION = '1005';//其他异常

   public function test_hit() {

       $phone_sh256 = hash('SHA256',request()->input('userPhone'));
        dd($phone_sh256);
       //撞库测试
   }

   private function helpWalletMakeReqData($json_data) {
       $secret = self::HELP_WALLET_PRIVATE_KEY;
       $iv = substr($secret,0,16);
       if (strlen($json_data) % 8) {
           $json_data = str_pad($json_data, strlen($json_data) + 8 - strlen($json_data) % 8, "\0");
       }
       $ret =  base64_encode(openssl_encrypt($json_data, "AES-128-CBC", $secret, OPENSSL_RAW_DATA | OPENSSL_NO_PADDING,$iv));
       return $ret;
   }

    public function test_register(Request $request) {
        echo '<pre>';
        $secret = self::HELP_WALLET_PRIVATE_KEY;
        $data = [
            "channel"=>"zlqb-union",
            "platform"=>1,
            "userPhone"=> $request->input('userPhone')
        ];
        $json_data = json_encode($data,JSON_UNESCAPED_UNICODE);
        print_r('reqData: '.$json_data .'<br/>');
        $reqData = $this->helpWalletMakeReqData($json_data);
        print_r('reqData encode: '.urlencode($reqData) .'<br/>');

        $paramsMap['version']  = $request->input('version', '1.0');
        $paramsMap['reqData'] = $reqData;
        $paramsMap['timestamp'] = $request->input('timestamp', '');
        $str = http_build_query($paramsMap);
        $str = urldecode($str);
        $sign =md5($str);
        print_r('sign: '. $sign);
        die;
//        openssl_encrypt($str, 'aes-256-cbc', $key, OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING, $iv);
//        $ret =  base64_encode(openssl_encrypt($json_data, "AES-128-CBC", $secret, OPENSSL_RAW_DATA,$iv));
        $ret =  base64_encode(openssl_encrypt($json_data, "AES-128-CBC", $secret, OPENSSL_RAW_DATA | OPENSSL_NO_PADDING,$iv));

        var_dump($ret);
//        $ver = openssl_decrypt(base64_decode($ret),"AES-128-CBC",$secret,OPENSSL_RAW_DATA,$iv);
//        openssl_decrypt($str, 'aes-256-cbc', $key, OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING, $iv);
        $ver = openssl_decrypt(base64_decode($ret),"AES-128-CBC",$secret,OPENSSL_RAW_DATA | OPENSSL_NO_PADDING,$iv);

        $allParams = request()->all();
        $sign = $allParams['sign'];
        $verifyData = $allParams;
        unset($verifyData['sign']);
        var_dump($verifyData);
//        dd($sign);
//        dd($allParams);
        $ret = $this->helpWalletVerifySign($verifyData,$sign);
        dd($ret);
        $secretKey = self::HELP_WALLET_PRIVATE_KEY;
//        $secretKey = "5962e90";
        $inputstr = json_encode(["phone_num"=>'1111111','name'=>'aaaa']);
        $base64Str = base64_encode(self::encode($secretKey,$inputstr));
        return $base64Str;
        die;
    }

    /**
     * @describle 助力钱包撞库, 验证是否老用户
     * @param Request $request
     * @return string
     * @author liChunLong
     * @date 2019-04-12
     */
   public function check(Request $request) {
      try{
          $userPhone =  $request->input('userPhone');
          $userId = User::where('phone_num_sha',$userPhone)->value('id');
          if (!empty($userId) && $userId > 0 ) {
                $ret = ['code'=>'0001', 'message'=>'老用户'];
                return json_encode($ret);
          }else {
              $ret = ['code'=>'0000', 'message'=>'新用户'];
              return json_encode($ret);
          }
      }catch (\Exception $e) {
          $ret = ['code'=>'9999', 'message'=>'net exception'];
          \Log::debug('助力钱包撞库异常，原因:'.$e->getMessage().' 请求参数：'.json_encode($request->all(),JSON_UNESCAPED_UNICODE));
          return json_encode($ret);
      }
   }

    /**
     * @describle 助力钱包 注册新用户
     * @param Request $request
     * @return string
     * @author liChunLong
     * @date 2019-04-15 21:00
     */
   public function register(Request $request)
   {
    $load_url = self::LOAD_URL.'?channel='.User::SOURCE_HELP_WALLET;
       
       try{
           $paramsMap['version']  = $request->input('version', '1.0');
           $paramsMap['reqData'] = $request->input('reqData', '');
           $paramsMap['timestamp'] = $request->input('timestamp', '');
           $paramsMap['sign'] = $sign = $request->input('sign', '');
           $missParams = '';
           foreach ($paramsMap as $k=>$v) {
               if (empty($v)) {
                   $missParams = $k;
                   break;
               }
           }
           if ($missParams) {
               \Log::debug('助力钱包注册失败，请求参数'.$missParams.'为空，所有请求：'.json_encode($request->all(),JSON_UNESCAPED_UNICODE));
               $ret = [
                   'code'=>self::UNION_CODE_PARAMS_EXCEPTION,
                   'message'=>$missParams . ' is empty',
                   'userFlag'=>self::UNION_USER_STATUS_OTHER,
                   'returnUrl'=>$load_url,
               ];
               return json_encode($ret);
           }
           unset($paramsMap['sign']);
           if (!$this->helpWalletVerifySign($paramsMap,$sign)) {
               \Log::debug('助力钱包注册失败，验签失败，所有请求：'.json_encode($request->all(),JSON_UNESCAPED_UNICODE));
               $ret = [
                   'code'=>self::UNION_CODE_SIGN_EXCEPTION,
                   'message'=>' verify sign is failure ',
                   'userFlag'=>self::UNION_USER_STATUS_OTHER,
                   'returnUrl'=>$load_url,
               ];
               return json_encode($ret);
           }
           $decryptData = $this->helpWalletDecrptData($paramsMap['reqData']);
           $userPhone = '';
           if ($decryptData && is_array($decryptData) && array_key_exists('userPhone',$decryptData)) {
               $userPhone = $decryptData['userPhone'];
           }
           if (empty($userPhone)) {
               \Log::debug('助力钱包注册失败，解密失败，所有请求：'.json_encode($request->all(),JSON_UNESCAPED_UNICODE));
               $ret = [
                   'code'=>self::UNION_CODE_DECRYPT_EXCEPTION,
                   'message'=>' decrypt data is failure ',
                   'userFlag'=>self::UNION_USER_STATUS_OTHER,
                   'returnUrl'=>$load_url,
               ];
               return json_encode($ret);
           }
           $newUserId = User::where('phone_num','=',$userPhone)->value('id');
           if ($newUserId && $newUserId > 0) {
               \Log::debug('助力钱包注册失败，重复注册，所有请求：'.json_encode($request->all(),JSON_UNESCAPED_UNICODE));
               $ret = [
                   'code'=>self::UNION_CODE_SUCCESS,
                   'message'=>'user has repeat register ',
                   'userFlag'=>self::UNION_USER_STATUS_OLD,
                   'returnUrl'=>$load_url,
               ];
               return json_encode($ret);
           }

           $rand_code =Strings::randomCode(6);
           User::createUser([
               'phone_num' => $userPhone,
               'password' => $rand_code,
               'source' => User::SOURCE_HELP_WALLET,
           ]);
           //推送助力钱包，快闪卡贷自动注册成功
           SmsTemplate::send(SmsTemplate::TEMPLATE_RZG_REGISTER,$userPhone,['name'=>$userPhone,'password'=>$rand_code]);
           \Log::debug('助力钱包注册成功，所有请求：'.json_encode($request->all(),JSON_UNESCAPED_UNICODE));
           $ret = [
               'code'=>self::UNION_CODE_SUCCESS,
               'message'=>'user register is success ',
               'userFlag'=>self::UNION_USER_STATUS_NEW,
               'returnUrl'=>$load_url,
           ];
           return json_encode($ret);
       }catch (\Exception $e) {
           \Log::debug('助力钱包注册失败，异常原因：'.$e->getMessage().'所有请求：'.json_encode($request->all(),JSON_UNESCAPED_UNICODE));
           $ret = [
               'code'=>self::UNION_CODE_NET_EXCEPTION,
               'message'=>'network exception ',
               'userFlag'=>self::UNION_USER_STATUS_OTHER,
               'returnUrl'=>$load_url,
           ];
           return json_encode($ret);
       }
   }

    /**
     * Description 验签
     * @Author liChunlong
     * @date 2019-04-12
     * @param $data
     * @param $sign
     * @return bool
     */
   private function helpWalletVerifySign($data,$sign){
//       ArrayTools::recursive_key_sort($data);
       $str = http_build_query($data);
       $str = urldecode($str);
       $md5_str =md5($str);
       return $md5_str == $sign ;
   }
    /**
     * Description 解密获取手机号
     * @Author liChunlong
     * @date 2019-04-12
     * @param $data
     * @return mixed
     */
   private function helpWalletDecrptData($reqData) {
       $secret = self::HELP_WALLET_PRIVATE_KEY;
       $iv = substr($secret,0,16);
       $decrypt_str = openssl_decrypt(base64_decode($reqData),"AES-128-CBC",$secret, OPENSSL_NO_PADDING,$iv);
       if (substr($decrypt_str,-1) != '}') {
           $last_site = strrpos($decrypt_str,'}');
           $decrypt_str = substr($decrypt_str,0,$last_site+1);
//            $decrypt_str = rtrim($decrypt_str);
       }
       return  json_decode($decrypt_str,true);
   }
}
